#encoding=utf8
from Config import Config
import Func, UserDict;

'''
对房间字典的操作

'''

def checkRoomExists(RoomId):
    '''
    检测房间是否存在于房间列表中
    @return: bool
    '''
    return Config.D_ROOM_DICT.has_key(RoomId)
def addRoomToRoomDict(oRoom):
    '''
    将房间添加入字典中
    @param oRoom:Room
    @return: bool 
    '''
    if (not oRoom):           
        return False;
    try:
        Config.D_ROOM_DICT[int(oRoom.get_id())] = oRoom;
        return True;
    except Exception, e:
        print str(e);
        return False;
def getRoomFromDictById(iRoomId):
    '''
    根据iRoomId取得Room对象
    @param iRoomId:int
    @return: Room 
    '''
    if(Config.D_ROOM_DICT.has_key(iRoomId)):
        return Config.D_ROOM_DICT[iRoomId]
    else:
        return None
    
    
    
    
    
    
def getRoomList(startPosition, count):
    '''
    取得起始位为startPosition并且长度为count的房间列表值
    @param startPosition:int    要取得的起始位置
    @param count: int    要取得长度
    @return: dictionary
    '''
    tmp = Config.D_ROOM_DICT
    roomCount = len(tmp)
    startPosition = int(startPosition)
    count = int(count)
    if(startPosition < 0):
        startPostion = 0
    if(startPosition > roomCount):
        startPosition = roomCount
    if(count > roomCount):
        count = roomCount
    if(count < 0):
        count = 1
    tmpDict = {}
    d = tmp.items()[startPosition:count + startPosition]
    for tmp in d:
        tmpDict[tmp[0]] = tmp[1]
    return tmpDict;

def addOrModUserToRoom(userObj, roomId):
    '''
            添加或修改用户到指定房间里
    @param userObj:用户对象
    @param roomId:房间ID
    @return:bool
    '''
    if not Config.D_ROOM_DICT:
        return False;
    if not userObj:
        return False;
    if not roomId:
        return False;
    if not Config.D_ROOM_DICT.has_key(roomId):
        return False;
    room = Config.D_ROOM_DICT[roomId];
   
    (room, userObj) = room.addUser(userObj);
    return addRoomToRoomDict(room); 


            
def delUserToRoom(userObj, roomId):
    '''
            删除指定房间里的用户
    @param userObj:用户对象
    @param roomId:房间ID
    @return:bool
    '''
    if not Config.D_ROOM_DICT:
        return False;
    if not userObj:
        return False;
    if not roomId:
        return False;
    if not Config.D_ROOM_DICT.has_key(roomId):
        return False;
    room = Config.D_ROOM_DICT[roomId];   
    (room, userObj) = room.delUser(userObj);
    return addRoomToRoomDict(room);  

def findUserInRoom(userId):
    '''
             搜索某用户在某个房间
    @param userId:用户id 
    @return: (bool,userObj,roomObj)
    '''
    result = False;
    if not userId:
        return (result, None, None);
    userTmp = UserDict.getUserFromUserDictById(userId);
    if not userTmp:
        return (result, None, None);
    if not Config.D_ROOM_DICT:
        return (result, userTmp, None);
#    for room in Config.D_ROOM_DICT.values():
#        userList=room.get_user_list();
#        if not userList:
#            continue;
#        for user in userList:
#            if toStr(user.get_user_id(),"-1")==toStr(userId,"-2"):
#                return (True,user,room);
#    
#    return (False,userTmp,None);    
    room = userTmp.get_room();
    
    if not room:
        result = True;
    return (result, userTmp, room);


def getUserStateinRoom(room):
    '''
    返回房间中所有用户状态人数
    @param room:房间
    @return: (ok,over,see) 
    '''
    if not room:
        return (0,0,0);
    okNum=0;
    overNum=0;
    seeNum=0;
    for user in room.get_user_list():
        if not user:
            continue;
        state=user.get_user_state();
        if state==Config.I_USER_GAME_STATE_OK:
            okNum+=1;
        elif state==Config.I_USER_GAME_STATE_OVER:
            overNum+=1;
        elif state==Config.I_USER_GAME_STATE_SEE:
            seeNum+=1;
    
    return (okNum,overNum,seeNum);
            
            
    





def getNextUserByPreUserId(room, preUserId):
    '''
        返回下一个用户
        @param preUserId:用户ID
        @param room：房间
        @return: User 
    '''
    if not room:
        return None;
    preUserId = Func.toInt(preUserId);
    if preUserId <= 0:
        return None;  
    indexTmp = 0;  
    try:
        for user in room.get_user_list():
            if user:
                if user.get_user_id() == preUserId:
                    return room.get_user_list()[indexTmp + 1];
            indexTmp += 1;
    except:
        return None;
                
    
def getCurrentUserByRoomId(roomId):
    '''
    返回房间里的当前游戏的用户
    @param roomId:房间ID 
    @return: userObj
    '''    
    room=getRoomFromDictById(roomId);
    if not room:
        return None;
    userList=room.get_user_list();
    if not userList:
        return None;
    for user in userList:
        if user.get_current_in_room():
            return user;
    return None;
            
        


 
    
    
def sendInfoToRoomAllUser(roomObj, cmd="", msg="", isPackage=True):
    '''
                广播信息给指定房间里的用户
    @param roomObj:房间对象
    @param cmd:命令
    @param msg:发送数据      
    '''
    if not roomObj:
        return;
    if not msg:
        return;
    userList = roomObj.get_user_list();
    if isPackage:
        msg = Func.toStr(cmd) + "#" + Func.toStr(msg);
    
    for user in userList:
        sock = user.get_socket();
#        print sock;
        if sock:
            if isPackage:
                sendRes = Func.toStr(user.get_user_nick_name()) + " " + Func.toStr(msg);
            else:
                sendRes = Func.toStr(msg);            
            Func.debugInfo("Func sendInfoToRoomAllUser send info:" + sendRes);                
            sock.sendLine(sendRes);   
    
